package com.fearless.test03;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class C {

    static Data3 data3=new Data3();


    public static void main(String[] args) {
        new Thread(()->{

            try {

                for (int i = 0; i <20 ; i++) {
                    data3.produce();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"生产者").start();


        new Thread(()->{

            try {
                for (int i = 0; i <20 ; i++) {
                    data3.consume();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"消费者").start();

    }

}

class Data3{

    Lock lock=new ReentrantLock(true);
    Condition condition = lock.newCondition();

    private int count=0;

    void consume() throws InterruptedException {

        lock.lock();

        try {
            while (count==0){
                condition.await();
            }

            System.out.println("当前库存是"+count+Thread.currentThread().getName()+"进行消费");
            count--;
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }


    void produce() throws InterruptedException {

        lock.lock();

            try {
                while (count>0){
                    condition.await();
                }

                System.out.println("当前库存是"+count+Thread.currentThread().getName()+"进行生产");
                count++;
                condition.signalAll();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }


    }



}